package com.agriculture.competition.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.agriculture.common.core.utils.DateUtils;
import com.agriculture.common.core.utils.StringUtils;
import com.agriculture.common.security.service.TokenService;
import com.agriculture.competition.domain.*;
import com.agriculture.competition.domain.vo.*;
import com.agriculture.competition.mapper.*;
import com.agriculture.competition.service.IJaCompetitionManageService;
import com.agriculture.system.api.domain.SysUser;
import com.agriculture.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 比赛管理Service业务层处理
 *
 * @author agriculture
 * @date 2024-11-12
 */
@Service
@Slf4j
public class JaCompetitionManageServiceImpl implements IJaCompetitionManageService {

    @Autowired
    private JaCompetitionManageMapper jaCompetitionManageMapper;

    @Autowired
    private JaFileMapper jaFileMapper;
    @Autowired
    private JaCompetitionUserMapper jaCompetitionUserMapper;
    @Autowired
    private JaCompetitionScoreMapper jaCompetitionScoreMapper;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private JaModelManageMapper jaModelManageMapper;
    @Autowired
    private JaCompetitionSolutionMapper jaCompetitionSolutionMapper;
    @Autowired
    private JaCompetitionGroupMapper jaCompetitionGroupMapper;
    @Autowired
    private JaCompetitionTeacherMapper jaCompetitionTeacherMapper;

    @Autowired
    private JaGroupUserMapper jaCompetitionUser;

    @Value("${role.teacher}")
    private String teacherRole;

    //总评委
    @Value("${role.judge}")
    private String judge;
    //评分
    @Value("${role.scoring}")
    private String scoring;


    @Value("${role.student}")
    private String studentRole;

    @Value("${role.approvalName}")
    private String approvalRole;

    @Value("${role.studentRoleName}")
    private String studentRoleName;


    @Autowired
    private JaCompetitionInvitationMapper jaCompetitionInvitationMapper;
    @Autowired
    private JaGroupUserMapper jaGroupUserMapper;

    /**
     * 查询比赛管理
     *
     * @param id 比赛管理主键
     * @return 比赛管理
     */
    @Override
    public JaCompetitionManage selectJaCompetitionManageById(Long id) {
        JaCompetitionTeacher jaCompetitionTeacher = new JaCompetitionTeacher();
        jaCompetitionTeacher.setUserType("0");
        jaCompetitionTeacher.setCompetitionId(id);
        List<JaCompetitionTeacher> jaCompetitionTeacherList = jaCompetitionTeacherMapper
                .selectJaCompetitionTeacherList(jaCompetitionTeacher);
        JaCompetitionTeacher jaCompetitionTeacher1 = new JaCompetitionTeacher();
        jaCompetitionTeacher1.setUserType("1");
        jaCompetitionTeacher1.setCompetitionId(id);
        List<JaCompetitionTeacher> jaCompetitionTeachers = jaCompetitionTeacherMapper.selectJaCompetitionTeacherList(jaCompetitionTeacher1);
        JaCompetitionManage jaCompetitionManage = jaCompetitionManageMapper.selectJaCompetitionManageById(id);
        jaCompetitionManage.setJaCompetitionTeachers(jaCompetitionTeachers);
        jaCompetitionManage.setJaCompetitionTeacherList(jaCompetitionTeacherList);
        return jaCompetitionManage;
    }

    /**
     * 查询比赛管理列表
     *
     * @param jaCompetitionManage 比赛管理
     * @return 比赛管理
     */
    @Override
    public List<JaCompetitionManageVo> selectJaCompetitionManageList(JaCompetitionManageVo jaCompetitionManage) {
        List<JaCompetitionManageVo> result = new ArrayList<>();
        LoginUser loginUser = tokenService.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("admin") || roles.contains(approvalRole) || roles.contains("common")) {
            jaCompetitionManage.setLoginUserId(null);
        } else {
            jaCompetitionManage.setLoginUserId(loginUser.getUserid());
        }


        List<JaCompetitionManageVo> jaCompetitionManages = jaCompetitionManageMapper.selectJaCompetitionManageList(jaCompetitionManage);
        if (!CollectionUtils.isEmpty(jaCompetitionManages)) {

            List<CompetitionGroupVo> competitionGroupVos = jaCompetitionGroupMapper.queryAllCompetitionGroupNum();
            Map<Long, Integer> joinGame = new HashMap<>();
            if (!CollectionUtils.isEmpty(competitionGroupVos)) {
                joinGame = competitionGroupVos.stream().collect(
                        Collectors.toMap(CompetitionGroupVo::getCompetitionId, CompetitionGroupVo::getGroupNum, (key1, key2) -> key2));
            }
            List<JaCompetitionUserVo> jaCompetitionUserVos1 = jaCompetitionSolutionMapper.queryCountByCompetitionId();
            //查询所有提交方案的人数
            // List<JaCompetitionUserVo> jaCompetitionUserVos1 = jaCompetitionSolutionMapper.querySolutionUserNum(null);
            Map<Long, Integer> submitSou = new HashMap<>();
            if (!CollectionUtils.isEmpty(jaCompetitionUserVos1)) {
                submitSou = jaCompetitionUserVos1.stream().collect(
                        Collectors.toMap(JaCompetitionUserVo::getCompetitionId, JaCompetitionUserVo::getEnrollment, (key1, key2) -> key2));
            }
            for (JaCompetitionManage jaCompetitionManage1 : jaCompetitionManages) {
                jaCompetitionManage1.setResultFlag("0");
                //判断比赛是否总评委打分结束
                JaCompetitionScore jaCompetitionScore = new JaCompetitionScore();
                jaCompetitionScore.setCompetitionId(jaCompetitionManage1.getId());
                List<JaCompetitionScore> jaCompetitionScores = jaCompetitionScoreMapper.selectJaCompetitionScoreList(jaCompetitionScore);
                if (CollectionUtil.isNotEmpty(jaCompetitionScores)) {
                    List<String> collect = jaCompetitionScores.stream().map(JaCompetitionScore::getResultScorer).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(collect)) {
                        jaCompetitionManage1.setResultFlag("1");
                    } else {
                        jaCompetitionManage1.setResultFlag("0");
                    }
                }

                //比赛的打分老师，和最终打分老师
                String scoringTeacher = "";
                String finalTeacher1 = "";
                JaCompetitionTeacher jaCompetitionTeacher = new JaCompetitionTeacher();
                jaCompetitionTeacher.setCompetitionId(jaCompetitionManage1.getId());
                List<JaCompetitionTeacher> jaCompetitionTeachers = jaCompetitionTeacherMapper.selectJaCompetitionTeacherList(jaCompetitionTeacher);
                if (CollectionUtil.isNotEmpty(jaCompetitionTeachers)) {
                    List<JaCompetitionTeacher> teacherList = jaCompetitionTeachers.stream().filter(record -> "1".equals(record.getUserType())).collect(Collectors.toList());
                    if (CollectionUtil.isNotEmpty(teacherList)) {
                        List<Long> collect1 = teacherList.stream().map(JaCompetitionTeacher::getUserId).collect(Collectors.toList());
                        if (collect1.contains(loginUser.getUserid())) {
                            jaCompetitionManage1.setFlag("2");
                        } else {
                            jaCompetitionManage1.setFlag("1");
                        }
//                        if (roles.contains("chiefjudge")) {
//                            jaCompetitionManage1.setFlag("2");
//                        } else {
//                            jaCompetitionManage1.setFlag("1");
//                        }
                    }
                    //0:评分老师,1最终评分老师
                    Map<String, List<JaCompetitionTeacher>> collect = jaCompetitionTeachers.stream().collect(Collectors.groupingBy(JaCompetitionTeacher::getUserType));// 按名称分组
                    List<JaCompetitionTeacher> scoreTeacher = collect.get("0");
                    List<JaCompetitionTeacher> finalTeacher = collect.get("1");

                    if (CollectionUtil.isNotEmpty(scoreTeacher)) {
                        scoringTeacher = scoreTeacher.stream().filter(e -> StringUtils.isNotBlank(e.getUserName()))
                                .map(JaCompetitionTeacher::getUserName) // 提取name字段
                                .collect(Collectors.joining(", "));
                    }

                    if (CollectionUtil.isNotEmpty(finalTeacher)) {
                        finalTeacher1 = finalTeacher.stream().filter(e -> StringUtils.isNotBlank(e.getUserName()))
                                .map(JaCompetitionTeacher::getUserName) // 提取name字段
                                .collect(Collectors.joining(", "));
                    }
                }

                JaCompetitionManageVo jaCompetitionManageVo = new JaCompetitionManageVo();
                BeanUtils.copyProperties(jaCompetitionManage1, jaCompetitionManageVo);
                if (joinGame.containsKey(jaCompetitionManage1.getId())) {
                    if (joinGame.get(jaCompetitionManage1.getId()) != null) {
                        jaCompetitionManageVo.setPeopleNum(Long.valueOf(joinGame.get(jaCompetitionManage1.getId())));
                    }
                }
                if (submitSou.containsKey(jaCompetitionManage1.getId())) {
                    if (submitSou.get(jaCompetitionManage1.getId()) != null) {
                        jaCompetitionManageVo.setSchemeNum(Long.valueOf(submitSou.get(jaCompetitionManage1.getId())));
                    }
                }
                jaCompetitionManageVo.setScoringTeacher(scoringTeacher);
                jaCompetitionManageVo.setFinalRatingTeacher(finalTeacher1);
                result.add(jaCompetitionManageVo);
            }
        }
        return result;
    }

    /**
     * 新增比赛管理
     *
     * @param jaCompetitionManage 比赛管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertJaCompetitionManage(JaCompetitionManage jaCompetitionManage) {
        jaCompetitionManage.setCreateTime(DateUtils.getNowDate());
        int count = jaCompetitionManageMapper.insertJaCompetitionManage(jaCompetitionManage);
        saveTeachers(jaCompetitionManage);
        return count;
    }

    /**
     * 修改比赛管理
     *
     * @param jaCompetitionManage 比赛管理
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateJaCompetitionManage(JaCompetitionManage jaCompetitionManage) {
        jaCompetitionManage.setUpdateTime(DateUtils.getNowDate());
        jaCompetitionTeacherMapper.deleteJaCompetitionTeacherByCompetitionId(jaCompetitionManage.getId());
        saveTeachers(jaCompetitionManage);
        return jaCompetitionManageMapper.updateJaCompetitionManage(jaCompetitionManage);
    }

    private void saveTeachers(JaCompetitionManage jaCompetitionManage) {
        //保存评分老师
        List<JaCompetitionTeacher> jaCompetitionTeacherList = jaCompetitionManage.getJaCompetitionTeacherList();
        if (CollectionUtil.isNotEmpty(jaCompetitionTeacherList)) {
            for (JaCompetitionTeacher jaCompetitionTeacher : jaCompetitionTeacherList) {
                jaCompetitionTeacher.setCompetitionId(jaCompetitionManage.getId());
                jaCompetitionTeacherMapper.insertJaCompetitionTeacher(jaCompetitionTeacher);
            }
        }
        //保存总评分老师
        List<JaCompetitionTeacher> jaCompetitionTeachers = jaCompetitionManage.getJaCompetitionTeachers();
        if (CollectionUtil.isNotEmpty(jaCompetitionTeachers)) {
            for (JaCompetitionTeacher jaCompetitionTeacher : jaCompetitionTeachers) {
                jaCompetitionTeacher.setCompetitionId(jaCompetitionManage.getId());
                jaCompetitionTeacherMapper.insertJaCompetitionTeacher(jaCompetitionTeacher);
            }
        }
    }

    /**
     * 批量删除比赛管理
     *
     * @param ids 需要删除的比赛管理主键
     * @return 结果
     */
    @Override
    public int deleteJaCompetitionManageByIds(Long[] ids) {
        return jaCompetitionManageMapper.deleteJaCompetitionManageByIds(ids);
    }

    /**
     * 删除比赛管理信息
     *
     * @param id 比赛管理主键
     * @return 结果
     */
    @Override
    public int deleteJaCompetitionManageById(Long id) {
        return jaCompetitionManageMapper.deleteJaCompetitionManageById(id);
    }

    @Override
    public List<JaFile> queryFiles(Long id, String flag) {
        List<JaFile> jaFiles = new ArrayList<>();
        try {
            JaFile jaFile = new JaFile();
            jaFile.setForeignKey(id);
            jaFile.setFlag(flag);
            jaFiles = jaFileMapper.selectJaFileList(jaFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jaFiles;
    }

    @Override
    public List<JaCompetitionUserVo> queryScore(Long id) {
        List<JaCompetitionUserVo> jaCompetitionUsers = new ArrayList<>();
        try {
            jaCompetitionUsers = jaCompetitionUserMapper.queryCompetitionUsers(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jaCompetitionUsers;
    }

    @Override
    public List<CompetitionGroupVo> queryScoreResult(Long id) {
        //查询某个比赛下的所有参赛队伍信息

        List<CompetitionGroupVo> groupVoList1 = new ArrayList<>();
        //查询比赛小组信息
        List<CompetitionGroupVo> groupVoList = new ArrayList<>();
        getScoreResult(id, groupVoList, true);
        LoginUser loginUser = tokenService.getLoginUser();
        //查询该比赛的评分老师集合  0:评分老师,1最终评分老师
        JaCompetitionTeacher jaCompetitionTeacher = new JaCompetitionTeacher();
        jaCompetitionTeacher.setCompetitionId(id);
        jaCompetitionTeacher.setUserType("0");
        List<JaCompetitionTeacher> jaCompetitionTeachers = jaCompetitionTeacherMapper.selectJaCompetitionTeacherList(jaCompetitionTeacher);

        if (CollectionUtil.isNotEmpty(jaCompetitionTeachers)) {
            List<Long> collect = jaCompetitionTeachers.stream().map(JaCompetitionTeacher::getUserId).collect(Collectors.toList());
            if (collect.contains(loginUser.getUserid())) {
                //查询参赛人的分数
                JaCompetitionScore jaCompetitionScore = new JaCompetitionScore();
                jaCompetitionScore.setCompetitionId(id);
                jaCompetitionScore.setScorerId(loginUser.getUserid());
                List<JaCompetitionScore> jaCompetitionScores = jaCompetitionScoreMapper.selectJaCompetitionScoreList(jaCompetitionScore);
                if (!CollectionUtils.isEmpty(jaCompetitionScores)) {
                    return groupVoList;
                } else {
                    List<CompetitionGroupVo> groupVoList2 = new ArrayList<>();
                    getScoreResult(id, groupVoList2, false);
                    return groupVoList2;
                }
            } else {
                return groupVoList1;
            }
        }

        //查询某个比赛下的所有参赛人
        // List<JaCompetitionUserVo> jaCompetitionUserVos = jaCompetitionUserMapper.queryCompetitionUsers(id);
//        if (CollectionUtils.isEmpty(jaCompetitionScores)) {
//            return groupVoList;
//        } else {
//            JaCompetitionScoreVo jaCompetitionScoreVo = new JaCompetitionScoreVo();
//            jaCompetitionScoreVo.setScorerId(loginUser.getUserid());
//            jaCompetitionScoreVo.setCompetitionId(id);
//            List<JaCompetitionUserVo> jaCompetitionUserVos1 = jaCompetitionUserMapper.queryCompetitionUserScore(jaCompetitionScoreVo);
//            return jaCompetitionUserVos1;
//        }
        return groupVoList1;
    }

    private void getScoreResult(Long id, List<CompetitionGroupVo> groupVoList, boolean flag) {
        //查询比赛下每个组的信息
        List<CompetitionGroupVo> competitionGroupVos = jaCompetitionGroupMapper.queryCompetitionGroupInfo(id);
        if (CollectionUtil.isNotEmpty(competitionGroupVos)) {
            Map<Long, List<CompetitionGroupVo>> collect =
                    competitionGroupVos.stream().filter(item -> item.getId() != null).
                            collect(Collectors.groupingBy(CompetitionGroupVo::getId)); // 按名称分组


            //查询登陆人给每个组打的分数
            LoginUser loginUser = tokenService.getLoginUser();
            Map<String, Object> map1 = new HashMap<>();
            map1.put("competitionId", id);
            map1.put("scorerId", loginUser.getUserid());
            List<CompetitionGroupVo> competitionGroupResults = jaCompetitionGroupMapper.queryCompetitionScore(map1);
            Map<Long, CompetitionGroupVo> groupScoreMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(competitionGroupResults)) {
                groupScoreMap = competitionGroupResults.stream().collect(Collectors.toMap(CompetitionGroupVo::getGroupId, a -> a, (k1, k2) -> k1));
            }

            //处理每个组展示的老师，学生集合字段
            for (Long groupid : collect.keySet()) {
                //查询每个小组的模型
                Map<String, Object> map = new HashMap<>();
                map.put("groupId", groupid);
                map.put("competitionId", id);
                List<JaCompetitionUserVo> jaCompetitionUserVos = jaCompetitionSolutionMapper.queryMldelId(map);
                List<CompetitionGroupVo> competitionGroupVos1 = collect.get(groupid);
                if (CollectionUtil.isNotEmpty(competitionGroupVos1)) {
                    CompetitionGroupVo vo = new CompetitionGroupVo();
                    BeanUtils.copyProperties(competitionGroupVos1.get(0), vo);
                    Map<String, List<CompetitionGroupVo>> collect1 = competitionGroupVos1.stream().filter(item -> item.getRole() != null).
                            collect(Collectors.groupingBy(CompetitionGroupVo::getRole));// 按名称分组

                    //0:老师1学生
                    if (collect1.containsKey("0")) {
                        List<CompetitionGroupVo> teacher = collect1.get("0");
                        if (CollectionUtil.isNotEmpty(teacher)) {
                            vo.setTeacherNames(teacher.get(0).getUserNames());
                            vo.setRole("0");
                        }

                    }
                    if (collect1.containsKey("1")) {
                        List<CompetitionGroupVo> student = collect1.get("1");
                        if (CollectionUtil.isNotEmpty(student)) {
                            vo.setStudentNames(student.get(0).getUserNames());
                            vo.setRole("1");
                        }
                    }
                    if (!flag) {
                        vo.setScore("");
                        if (CollectionUtil.isNotEmpty(jaCompetitionUserVos)) {
                            vo.setModelId(jaCompetitionUserVos.get(0).getModelId());
                        }
                    }
                    if (flag) {
                        if (CollectionUtil.isNotEmpty(jaCompetitionUserVos)) {
                            vo.setModelId(jaCompetitionUserVos.get(0).getModelId());
                        }
                        if (groupScoreMap != null && groupScoreMap.size() > 0) {
                            CompetitionGroupVo competitionGroupVo = groupScoreMap.get(vo.getId());
                            if (competitionGroupVo != null) {
                                vo.setScore(competitionGroupVo.getScore());
                            }
                        }
                    }
                    groupVoList.add(vo);
                }
            }
        }
    }


    private void getScoreResultFinal(Long id, List<CompetitionGroupVo> groupVoList, boolean flag) {
        //查询比赛下每个组的信息
        List<CompetitionGroupVo> competitionGroupVos = jaCompetitionGroupMapper.queryCompetitionGroupInfo(id);
        if (CollectionUtil.isNotEmpty(competitionGroupVos)) {
            Map<Long, List<CompetitionGroupVo>> collect =
                    competitionGroupVos.stream().filter(item -> item.getId() != null).
                            collect(Collectors.groupingBy(CompetitionGroupVo::getId)); // 按名称分组


            //查询登陆人给每个组打的分数
            Map<String, Object> map1 = new HashMap<>();
            map1.put("competitionId", id);
            List<CompetitionGroupVo> competitionGroupResults = jaCompetitionGroupMapper.queryCompetitionScore(map1);
            Map<Long, CompetitionGroupVo> groupScoreMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(competitionGroupResults)) {
                groupScoreMap = competitionGroupResults.stream().collect(Collectors.toMap(CompetitionGroupVo::getGroupId, a -> a, (k1, k2) -> k1));
            }
            //处理每个组展示的老师，学生集合字段
            for (Long groupid : collect.keySet()) {
                //查询每个小组的模型
                Map<String, Object> map = new HashMap<>();
                map.put("groupId", groupid);
                map.put("competitionId", id);
                List<JaCompetitionUserVo> jaCompetitionUserVos = jaCompetitionSolutionMapper.queryMldelId(map);

                List<CompetitionGroupVo> competitionGroupVos1 = collect.get(groupid);
                if (CollectionUtil.isNotEmpty(competitionGroupVos1)) {
                    CompetitionGroupVo vo = new CompetitionGroupVo();
                    BeanUtils.copyProperties(competitionGroupVos1.get(0), vo);
                    Map<String, List<CompetitionGroupVo>> collect1 = competitionGroupVos1.stream().filter(item -> item.getRole() != null).
                            collect(Collectors.groupingBy(CompetitionGroupVo::getRole));// 按名称分组

                    //0:老师1学生
                    if (collect1.containsKey("0")) {
                        List<CompetitionGroupVo> teacher = collect1.get("0");
                        if (CollectionUtil.isNotEmpty(teacher)) {
                            vo.setTeacherNames(teacher.get(0).getUserNames());
                            vo.setRole("0");
                        }

                    }
                    if (collect1.containsKey("1")) {
                        List<CompetitionGroupVo> student = collect1.get("1");
                        if (CollectionUtil.isNotEmpty(student)) {
                            vo.setStudentNames(student.get(0).getUserNames());
                            vo.setRole("1");
                        }
                    }
                    if (!flag) {
                        vo.setScore("");
                        if (CollectionUtil.isNotEmpty(jaCompetitionUserVos)) {
                            vo.setModelId(jaCompetitionUserVos.get(0).getModelId());
                        }
                    }
                    if (flag) {
                        if (CollectionUtil.isNotEmpty(jaCompetitionUserVos)) {
                            vo.setModelId(jaCompetitionUserVos.get(0).getModelId());
                        }
                        if (groupScoreMap != null && groupScoreMap.size() > 0) {
                            CompetitionGroupVo competitionGroupVo = groupScoreMap.get(vo.getId());
                            if (competitionGroupVo != null) {
                                vo.setScore(competitionGroupVo.getScore());
                                vo.setResultScorer(competitionGroupVo.getResultScorer());
                            }
                        }
                    }
                    groupVoList.add(vo);
                }
            }
        }
    }

    @Override
    public List<CompetitionGroupVo> queryScoreFinal(Long id) {
        LoginUser loginUser = tokenService.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        List<CompetitionGroupVo> groupVoList = new ArrayList<>();
        Boolean bull = false;
        if (roles.contains("common")) {
            bull = true;
        } else {
            //打最终分的老师  0:评分老师,1最终评分老师
            JaCompetitionTeacher jaCompetitionTeacher = new JaCompetitionTeacher();
            jaCompetitionTeacher.setCompetitionId(id);
            jaCompetitionTeacher.setUserType("1");
            List<JaCompetitionTeacher> jaCompetitionTeachers = jaCompetitionTeacherMapper.selectJaCompetitionTeacherList(jaCompetitionTeacher);
            if (CollectionUtil.isEmpty(jaCompetitionTeachers)) {
                bull = false;
            }
            if (CollectionUtil.isNotEmpty(jaCompetitionTeachers)) {
                List<Long> collect = jaCompetitionTeachers.stream().map(JaCompetitionTeacher::getUserId).collect(Collectors.toList());
                if (!collect.contains(loginUser.getUserid())) {
                    bull = false;
                } else {
                    bull = true;
                }
            }
        }

        //查询某个比赛下的所有参赛人
        if (bull) {
            getScoreResult(id, groupVoList, true);
            if (!CollectionUtils.isEmpty(groupVoList)) {
                //查询参赛人的分数
                List<JaCompetitionScore> jaCompetitionScores = jaCompetitionScoreMapper.queryCompetitionScoreByCompetitionId(id);
                //某个组对应的所有老师的分
                Map<Long, List<JaCompetitionScore>> collect = new HashMap<>();
                if (!CollectionUtils.isEmpty(jaCompetitionScores)) {
                    collect = jaCompetitionScores.stream().collect(Collectors.groupingBy(JaCompetitionScore::getGroupId));
                }
                for (int i = 0; i < groupVoList.size(); i++) {
                    if (collect.containsKey(groupVoList.get(i).getId())) {
                        List<JaCompetitionScore> jaCompetitionScores1 = collect.get(groupVoList.get(i).getId());
                        groupVoList.get(i).setScores(jaCompetitionScores1);
                        if (!CollectionUtils.isEmpty(jaCompetitionScores1)) {
                            groupVoList.get(i).setResultScorer(jaCompetitionScores1.get(0).getResultScorer());
                            groupVoList.get(i).setOrderNum(jaCompetitionScores1.get(0).getOrderNum());
                        }
                    }
                }
                groupVoList
                        .sort(Comparator.comparing(CompetitionGroupVo::getOrderNum, Comparator.nullsLast(Comparator.naturalOrder())));
            }
        }
        return groupVoList;
    }


    @Override
    public List<CompetitionGroupVo> queryScoreFinalResult(Long id) {

        JaCompetitionManage jaCompetitionManage = jaCompetitionManageMapper.selectJaCompetitionManageById(id);
        if (jaCompetitionManage == null) {
            return new ArrayList<>();
        }
        String resultStatus = jaCompetitionManage.getResultStatus();

        //查询某个比赛下的所有参赛人
        List<CompetitionGroupVo> groupVoList = new ArrayList<>();
        if ("1".equals(resultStatus)) {
            getScoreResultFinal(id, groupVoList, true);
            if (!CollectionUtils.isEmpty(groupVoList)) {
                //查询参赛人的分数
                List<JaCompetitionScore> jaCompetitionScores = jaCompetitionScoreMapper.queryCompetitionScoreByCompetitionId(id);
                //某个组对应的所有老师的分
                Map<Long, List<JaCompetitionScore>> collect = new HashMap<>();
                if (!CollectionUtils.isEmpty(jaCompetitionScores)) {
                    collect = jaCompetitionScores.stream().collect(Collectors.groupingBy(JaCompetitionScore::getGroupId));
                }
                for (int i = 0; i < groupVoList.size(); i++) {
                    if (collect.containsKey(groupVoList.get(i).getId())) {
                        List<JaCompetitionScore> jaCompetitionScores1 = collect.get(groupVoList.get(i).getId());
                        groupVoList.get(i).setScores(jaCompetitionScores1);
                        if (!CollectionUtils.isEmpty(jaCompetitionScores1)) {
                            groupVoList.get(i).setResultScorer(jaCompetitionScores1.get(0).getResultScorer());
                            groupVoList.get(i).setOrderNum(jaCompetitionScores1.get(0).getOrderNum());
                        }
                    }
                }
                groupVoList
                        .sort(Comparator.comparing(CompetitionGroupVo::getOrderNum, Comparator.nullsLast(Comparator.naturalOrder())));
            }
        }
        return groupVoList;
    }


    @Override
    public List<JaCompetitionManageVo> queryCompetitionByStatus() {
        List<JaCompetitionManageVo> list = new ArrayList<>();
        JaCompetitionManageVo jaCompetitionManage = new JaCompetitionManageVo();
        //查询显示的
        jaCompetitionManage.setStatus(null);
        jaCompetitionManage.setIsShow("1");
        List<JaCompetitionManageVo> jaCompetitionManages = jaCompetitionManageMapper.selectJaCompetitionManageList1(jaCompetitionManage);

        if (!CollectionUtils.isEmpty(jaCompetitionManages)) {
            //查所有比赛的参赛人数
            List<CompetitionGroupVo> groupVoList = jaCompetitionGroupMapper.queryAllCompetitionGroupNum();
            // List<JaCompetitionUserVo> jaCompetitionUserVos = jaCompetitionUserMapper.queryUserCount();
            // List<JaCompetitionUserVo> jaCompetitionUserVos = jaCompetitionUserMapper.queryCompetitionByUser(null);
            Map<Long, Integer> joinGame = new HashMap<>();
            if (!CollectionUtils.isEmpty(groupVoList)) {
                joinGame = groupVoList.stream().collect(
                        Collectors.toMap(CompetitionGroupVo::getCompetitionId, CompetitionGroupVo::getGroupNum, (key1, key2) -> key2));
            }
            for (JaCompetitionManage jaCompetitionManage1 : jaCompetitionManages) {
                JaCompetitionManageVo jaCompetitionManageVo = new JaCompetitionManageVo();
                BeanUtils.copyProperties(jaCompetitionManage1, jaCompetitionManageVo);
                //参赛人员数
                if (joinGame.containsKey(jaCompetitionManage1.getId())) {
                    if (joinGame.get(jaCompetitionManage1.getId()) != null) {
                        jaCompetitionManageVo.setPeopleNum(Long.valueOf(joinGame.get(jaCompetitionManage1.getId())));
                    }
                }
                long l = diffDate(new Date(), jaCompetitionManage1.getRegistrationDeadline());
                jaCompetitionManageVo.setRemainingTime(l);
                list.add(jaCompetitionManageVo);
            }
        }
        return list;
    }

    @Override
    public Integer queryCompetitionCount(Long id) {
        Integer integer = 0;
        JaCompetitionGroup jaCompetitionGroup = new JaCompetitionGroup();
        jaCompetitionGroup.setCompetitionId(id);
        List<JaCompetitionGroup> jaCompetitionGroups = jaCompetitionGroupMapper.selectJaCompetitionGroupList(jaCompetitionGroup);

        if (CollectionUtil.isNotEmpty(jaCompetitionGroups)) {
            integer = jaCompetitionGroups.size();
        }
//        List<JaCompetitionUserVo> jaCompetitionUserVos = jaCompetitionUserMapper.queryUserCount();
//        Map<Long, Integer> joinGame = new HashMap<>();
//        if (!CollectionUtils.isEmpty(jaCompetitionUserVos)) {
//            joinGame = jaCompetitionUserVos.stream().collect(
//                    Collectors.toMap(JaCompetitionUserVo::getCompetitionId, JaCompetitionUserVo::getEnrollment, (key1, key2) -> key2));
//        }
//        if (joinGame.containsKey(id)) {
//            integer = joinGame.get(id);
//        }
        return integer;
    }


    public long diffDate(Date startDate, Date endDate) {
        long millisecondsPerDay = 24 * 60 * 60 * 1000;
        long daysBetween = (endDate.getTime() - startDate.getTime()) / millisecondsPerDay;
        if (daysBetween < 0) {
            daysBetween = 0L;
        }
        return daysBetween;
    }

    /**
     * 参赛
     *
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int participateInCompetition(CompetitionGroupVo vo) {
        //获取当前登录用户
        try {
            LoginUser loginUser = tokenService.getLoginUser();
            if ("admin".equals(loginUser.getUsername())) {
                throw new RuntimeException("超管不能参加比赛！");
            }

            //登陆人
            JaGroupUser jaGroupUser = new JaGroupUser();
            jaGroupUser.setUserName(loginUser.getUsername());
            jaGroupUser.setUserId(loginUser.getUserid());
            Set<String> roles = loginUser.getRoles();
            //'0:老师1学生
            if (roles.contains(studentRoleName)) {
                jaGroupUser.setRole("1");
                jaGroupUser.setRoleType("1");
            } else {
                jaGroupUser.setRole("0");
                jaGroupUser.setRoleType("0");
            }
            //1:已邀请 0：已加入
            jaGroupUser.setStatus("0");

            List<JaGroupUser> listUser = new ArrayList<>();
            //1:已邀请 0：已加入
            List<JaGroupUser> joinUser1 = vo.getListUser();
            if (CollectionUtil.isNotEmpty(joinUser1)) {
                for (JaGroupUser jaGroupUser1 : joinUser1) {
                    jaGroupUser1.setRole(jaGroupUser1.getRoleType());
                    JaCompetitionInvitation jaCompetitionInvitation = new JaCompetitionInvitation();
                    jaCompetitionInvitation.setInvitedPerson(jaGroupUser1.getUserId());
                    jaCompetitionInvitation.setCompetitionId(vo.getCompetitionId());
                    String status1 = jaCompetitionInvitationMapper.queryStatusUser(jaCompetitionInvitation);
                    jaGroupUser1.setStatus(status1);
                }
                List<String> collect1 = joinUser1.stream().map(JaGroupUser::getStatus).collect(Collectors.toList());

//                Map<String, List<JaGroupUser>> collect = joinUser1.stream().filter(item -> StringUtils.isNotBlank(item.getStatus())).
//                        collect(Collectors.groupingBy(JaGroupUser::getStatus));// 按名称分组
                if (CollectionUtil.isNotEmpty(collect1)) {
                    if (collect1.contains("1") || collect1.contains("2")) {
                        //没有加入的人
                        List<JaGroupUser> filterList = joinUser1.stream().
                                filter(item -> StringUtils.isNotBlank(item.getStatus()) && !"0".equals(item.getStatus())).collect(Collectors.toList());
                        String namesConcatenated = filterList.stream().filter(e -> StringUtils.isNotBlank(e.getUserName()))
                                .map(JaGroupUser::getUserName) // 提取name字段
                                .collect(Collectors.joining(", ")); // 使用","作为分隔符拼接
                        throw new RuntimeException("这些人[" + namesConcatenated + "]还没接受邀请,或者拒绝了，请提醒被邀请人加入或者删除被邀请人！");
                    }
                }
                joinUser1.add(jaGroupUser);

                listUser.addAll(joinUser1);
            } else {
                listUser.add(jaGroupUser);
                vo.setListUser(listUser);
            }

            List<JaGroupUser> joinUser = listUser.stream().
                    filter(user -> StringUtils.isNotBlank(user.getStatus()) && "0".equals(user.getStatus())).
                    collect(Collectors.toList());

            if (CollectionUtil.isEmpty(joinUser)) {
                throw new RuntimeException("有未接受邀请的组员，请提醒组员去同意邀请！");
            }
            //0:老师1学生  人数判断
            Map<String, List<JaGroupUser>> collect = joinUser.stream().collect(Collectors.groupingBy(JaGroupUser::getRole));
            //报名的老师
            List<JaGroupUser> jaGroupUsers = collect.get("0");
            //报名的学生
            List<JaGroupUser> jaGroupStudent = collect.get("1");
            int student = 0;
            int teacher = 0;
            if (CollectionUtil.isNotEmpty(jaGroupUsers)) {
                teacher = jaGroupUsers.size();
            }
            if (CollectionUtil.isNotEmpty(jaGroupStudent)) {
                student = jaGroupStudent.size();
            }
            //查比赛详情
            JaCompetitionManage jaCompetitionManage = jaCompetitionManageMapper.selectJaCompetitionManageById(vo.getCompetitionId());

            Integer groupMax = jaCompetitionManage.getGroupMax();
            Integer groupTeacherMax = jaCompetitionManage.getGroupTeacherMax();

            if (groupTeacherMax == 0 && CollectionUtil.isNotEmpty(jaGroupUsers)) {
                throw new RuntimeException("该比赛不允许老师参赛！");
            }
            if (student > groupMax) {
                throw new RuntimeException("参赛学生人数超过系统设置的【" + groupMax + "】个学生人数！");
            }
            if (teacher > groupTeacherMax) {
                throw new RuntimeException("参赛老师人数超过系统设置的【" + groupTeacherMax + "】个老师人数！");
            }

            //打分老师不能参赛
            //打分的老师
            JaCompetitionTeacher jaCompetitionTeacher = new JaCompetitionTeacher();
            jaCompetitionTeacher.setCompetitionId(vo.getCompetitionId());
            List<JaCompetitionTeacher> jaCompetitionTeachers = jaCompetitionTeacherMapper.selectJaCompetitionTeacherList(jaCompetitionTeacher);
            //获取打分老师也报名的名单
            if (CollectionUtil.isNotEmpty(jaGroupUsers)) {
                Map<Long, JaGroupUser> collect1 = jaGroupUsers.stream().collect(Collectors.toMap(JaGroupUser::getUserId, obj -> obj));
                List<JaCompetitionTeacher> collect2 = jaCompetitionTeachers.stream().filter(obj -> collect1.containsKey(obj.getUserId()))
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect2)) {
                    String namesConcatenated = collect2.stream().filter(e -> StringUtils.isNotBlank(e.getUserName()))
                            .map(JaCompetitionTeacher::getUserName) // 提取name字段
                            .collect(Collectors.joining(", ")); // 使用","作为分隔符拼接
                    throw new RuntimeException("这些老师【" + namesConcatenated + "】是本比赛的打分老师，不能参赛！");
                }
            }


            //查比赛下的学生
            Map<String, Object> map = new HashMap<>();
            map.put("competitionId", vo.getCompetitionId());
            //0:老师1学生
            map.put("role", "1");
            List<CompetitionGroupResult> competitionGroupResults = jaCompetitionGroupMapper.queryCompetitionGroupUsers(map);
            if (CollectionUtil.isNotEmpty(competitionGroupResults) && CollectionUtil.isNotEmpty(jaGroupStudent)) {
                Map<Long, JaGroupUser> student1 = jaGroupStudent.stream().collect(Collectors.toMap(JaGroupUser::getUserId, obj -> obj));
                List<JaGroupUser> studentCompetition = competitionGroupResults.stream().filter(obj -> student1.containsKey(obj.getUserId()))
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(studentCompetition)) {
                    String namesConcatenated = studentCompetition.stream().filter(e -> StringUtils.isNotBlank(e.getUserName()))
                            .map(JaGroupUser::getUserName) // 提取name字段
                            .collect(Collectors.joining(", ")); // 使用","作为分隔符拼接
                    throw new RuntimeException("这些学生【" + namesConcatenated + "】已参加本比赛，不能重复参赛！");
                }
            }
            //保存比赛团体关联表

            JaCompetitionGroup jaCompetitionGroup = new JaCompetitionGroup();
            BeanUtils.copyProperties(vo, jaCompetitionGroup);
            jaCompetitionGroup.setCreateUser(loginUser.getUsername());
            jaCompetitionGroup.setCreateTime(new Date());
            jaCompetitionGroupMapper.insertJaCompetitionGroup(jaCompetitionGroup);
            //保存参赛人员
            //已加入的才能参赛
            for (JaGroupUser user : listUser) {
                user.setRole(user.getRoleType());
                user.setGroupId(jaCompetitionGroup.getId());
                user.setCreateUser(loginUser.getUsername());
                user.setCreateTime(new Date());
                jaCompetitionUser.insertJaGroupUser(user);
            }
//            Map map = jaCompetitionUserMapper.queryUserById(loginUser.getUserid());
//            if (map != null) {
//                String nickName = (String) map.get("nickName");
//                jaCompetitionUser.setNickUser(nickName);
//            }
        } catch (Exception e) {
            log.error("参加比赛失败", e);
            throw new RuntimeException(e.getMessage());
        }
        return 0;
    }

    /**
     * 我的比赛
     *
     * @return
     */
    @Override
    public List<JaCompetitionManageVo> selfCompetition(JaCompetitionManageVo queryParam) {
        List<JaCompetitionManageVo> result = new ArrayList<>();

        LoginUser loginUser = tokenService.getLoginUser();
        JaCompetitionUser jaCompetitionUser = new JaCompetitionUser();
        jaCompetitionUser.setUserId(loginUser.getUserid());

        //登录人的所有参赛小组
        List<CompetitionGroupVo> jaCompetitionGroups = jaCompetitionGroupMapper.queryLoginUserGroup(loginUser.getUserid());
        Map<Long, CompetitionGroupVo> groupVoMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(jaCompetitionGroups)) {
            groupVoMap = jaCompetitionGroups.stream().collect(Collectors.toMap(CompetitionGroupVo::getCompetitionId, a -> a, (k1, k2) -> k1));
        }
        //查询登陆人所参加的所有比赛
        Map<String, Object> map = new HashMap<>();
        map.put("userId", loginUser.getUserid());
        List<CompetitionGroupResult> competitionGroupResults = jaCompetitionGroupMapper.queryCompetitionGroupUsers(map);
        //List<JaCompetitionUser> jaCompetitionUsers = jaCompetitionUserMapper.selectJaCompetitionUserList(jaCompetitionUser);
        if (!CollectionUtils.isEmpty(competitionGroupResults)) {
            //参赛ids    //查询我的参赛数据
            List<Long> collect = competitionGroupResults.stream().map(e -> e.getCompetitionId()).collect(Collectors.toList());
            JaCompetitionManageVo jaCompetitionManage = new JaCompetitionManageVo();
            jaCompetitionManage.setIds(collect);
            jaCompetitionManage.setId(queryParam.getId());
            jaCompetitionManage.setCompetitionName(queryParam.getCompetitionName());
            jaCompetitionManage.setStatus(queryParam.getStatus());
            jaCompetitionManage.setStartTime(queryParam.getStartTime());
            jaCompetitionManage.setEndTime(queryParam.getEndTime());
            jaCompetitionManage.setIsSubmit(queryParam.getIsSubmit());
            List<JaCompetitionManageVo> jaCompetitionManages = jaCompetitionManageMapper.selectJaCompetitionManageList(jaCompetitionManage);

            //查我参加的参赛的人数
            List<CompetitionGroupVo> competitionGroupVos = jaCompetitionGroupMapper.queryAllCompetitionGroupNum();
            Map<Long, Integer> collect1 = new HashMap<>();
            if (!CollectionUtils.isEmpty(competitionGroupVos)) {
                collect1 = competitionGroupVos.stream().collect(
                        Collectors.toMap(CompetitionGroupVo::getCompetitionId, CompetitionGroupVo::getGroupNum, (key1, key2) -> key2));
            }
            //查询所有提交方案的人数
            List<JaCompetitionUserVo> jaCompetitionUserVos1 = jaCompetitionSolutionMapper.queryCountByCompetitionId();
            Map<Long, Integer> submitSou = new HashMap<>();
            if (!CollectionUtils.isEmpty(jaCompetitionUserVos1)) {
                submitSou = jaCompetitionUserVos1.stream().collect(
                        Collectors.toMap(JaCompetitionUserVo::getCompetitionId, JaCompetitionUserVo::getEnrollment, (key1, key2) -> key2));
            }
            //组装结果。将参赛人数加进去
            if (!CollectionUtils.isEmpty(jaCompetitionManages)) {
                for (JaCompetitionManageVo jaCompetitionManageVo : jaCompetitionManages) {
                    //比赛的打分老师，和最终打分老师
                    String scoringTeacher = "";
                    String finalTeacher1 = "";
                    JaCompetitionTeacher jaCompetitionTeacher = new JaCompetitionTeacher();
                    jaCompetitionTeacher.setCompetitionId(jaCompetitionManageVo.getId());
                    List<JaCompetitionTeacher> jaCompetitionTeachers = jaCompetitionTeacherMapper.selectJaCompetitionTeacherList(jaCompetitionTeacher);
                    if (CollectionUtil.isNotEmpty(jaCompetitionTeachers)) {
                        //0:评分老师,1最终评分老师
                        Map<String, List<JaCompetitionTeacher>> teachers = jaCompetitionTeachers.stream().collect(Collectors.groupingBy(JaCompetitionTeacher::getUserType));// 按名称分组
                        List<JaCompetitionTeacher> scoreTeacher = teachers.get("0");
                        List<JaCompetitionTeacher> finalTeacher = teachers.get("1");

                        if (CollectionUtil.isNotEmpty(scoreTeacher)) {
                            scoringTeacher = scoreTeacher.stream().filter(e -> StringUtils.isNotBlank(e.getUserName()))
                                    .map(JaCompetitionTeacher::getUserName) // 提取name字段
                                    .collect(Collectors.joining(", "));
                        }

                        if (CollectionUtil.isNotEmpty(finalTeacher)) {
                            finalTeacher1 = finalTeacher.stream().filter(e -> StringUtils.isNotBlank(e.getUserName()))
                                    .map(JaCompetitionTeacher::getUserName) // 提取name字段
                                    .collect(Collectors.joining(", "));
                        }
                    }


                    if (collect1.containsKey(jaCompetitionManageVo.getId())) {
                        if (collect1.get(jaCompetitionManageVo.getId()) != null) {
                            jaCompetitionManageVo.setPeopleNum(Long.valueOf(collect1.get(jaCompetitionManageVo.getId())));
                        }
                    }
                    if (submitSou.containsKey(jaCompetitionManageVo.getId())) {
                        if (submitSou.get(jaCompetitionManageVo.getId()) != null) {
                            jaCompetitionManageVo.setSchemeNum(Long.valueOf(submitSou.get(jaCompetitionManageVo.getId())));
                        }
                    }
                    if (StringUtils.isBlank(jaCompetitionManageVo.getIsSubmit())) {
                        jaCompetitionManageVo.setIsSubmit("0");
                    }

                    if (groupVoMap.containsKey(jaCompetitionManageVo.getId())) {
                        CompetitionGroupVo competitionGroupVo = groupVoMap.get(jaCompetitionManageVo.getId());
                        if (competitionGroupVo != null) {
                            jaCompetitionManageVo.setGroupId(competitionGroupVo.getId());
                        }
                    }
                    jaCompetitionManageVo.setFinalRatingTeacher(finalTeacher1);
                    jaCompetitionManageVo.setScoringTeacher(scoringTeacher);
                    result.add(jaCompetitionManageVo);
                }
            }
        }
        return result;
    }


    /**
     * 提交方案
     *
     * @param jaCompetitionSolutionVo
     * @return
     */
    @Override
    public boolean submitSolution(JaCompetitionSolutionVo jaCompetitionSolutionVo) {
        try {
            //先删除再新增
            //LoginUser loginUser = tokenService.getLoginUser();
            JaCompetitionSolution jaCompetitionSolution1 = new JaCompetitionSolution();
            jaCompetitionSolution1.setGroupId(jaCompetitionSolutionVo.getGroupId());
            jaCompetitionSolution1.setCompetitionId(jaCompetitionSolutionVo.getCompetitionId());
            jaCompetitionSolutionMapper.deleteJaCompetitionSolution(jaCompetitionSolution1);

            JaCompetitionSolution jaCompetitionSolution = new JaCompetitionSolution();
            jaCompetitionSolution.setGroupId(jaCompetitionSolutionVo.getGroupId());
            BeanUtils.copyProperties(jaCompetitionSolutionVo, jaCompetitionSolution);
            jaCompetitionSolution.setIsSubmit("1");
            jaCompetitionSolution.setGroupId(jaCompetitionSolutionVo.getGroupId());
            jaCompetitionSolutionMapper.insertJaCompetitionSolution(jaCompetitionSolution);
        } catch (BeansException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean saveScore(JaCompetitionScoreVo jaCompetitionScoreVo) {
        try {
            LoginUser loginUser = tokenService.getLoginUser();
            List<JaCompetitionScoreVo> groupVoList = jaCompetitionScoreVo.getScoreVoList();
            // List<JaCompetitionScore> userScores = jaCompetitionSolutionVo.getUserScore();
            if (!CollectionUtils.isEmpty(groupVoList)) {
                // List<Long> collect = userScores.stream().map(e -> e.getUserId()).collect(Collectors.toList());
                JaCompetitionScore jaCompetitionScore = new JaCompetitionScore();
                jaCompetitionScore.setScorerId(loginUser.getUserid());
                jaCompetitionScore.setCompetitionId(jaCompetitionScoreVo.getCompetitionId());
                // jaCompetitionScore.setStudentIds(collect);
                List<JaCompetitionScore> jaCompetitionScores = jaCompetitionScoreMapper.selectJaCompetitionScoreList(jaCompetitionScore);

                Map<Long, JaCompetitionScore> group = new HashMap<>();
                if (!CollectionUtils.isEmpty(jaCompetitionScores)) {
                    group = jaCompetitionScores.stream().collect(Collectors.toMap(JaCompetitionScore::getGroupId, a -> a, (k1, k2) -> k1));
                }
                for (JaCompetitionScoreVo userScore : groupVoList) {
                    if (group.containsKey(userScore.getGroupId())) {
                        //条件
                        JaCompetitionScore jaCompetitionScore1 = new JaCompetitionScore();
                        jaCompetitionScore1.setGroupId(userScore.getGroupId());
                        jaCompetitionScore1.setCompetitionId(userScore.getCompetitionId());
                        jaCompetitionScore1.setScorerId(loginUser.getUserid());
                        //改分
                        jaCompetitionScore1.setScore(userScore.getScore());
                        jaCompetitionScore1.setUpdateUser(loginUser.getUserid());
                        jaCompetitionScoreMapper.updateJaCompetitionScoreByUser(jaCompetitionScore1);
                    } else {
                        JaCompetitionScore jaCompetitionScore1 = new JaCompetitionScore();
                        BeanUtils.copyProperties(userScore, jaCompetitionScore1);
                        jaCompetitionScore1.setScorerId(loginUser.getUserid());
                        jaCompetitionScore1.setCreateUser(loginUser.getUserid());
                        jaCompetitionScoreMapper.insertJaCompetitionScore(jaCompetitionScore1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean saveScoreResult(JaCompetitionScoreVo jaCompetitionScoreVo) {
        try {
            LoginUser loginUser = tokenService.getLoginUser();
            List<JaCompetitionScoreVo> scoreVoList = jaCompetitionScoreVo.getScoreVoList();
            if (!CollectionUtils.isEmpty(scoreVoList)) {
                scoreVoList
                        .sort(Comparator.comparing(JaCompetitionScoreVo::getResultScorer, Comparator.nullsLast(Comparator.reverseOrder())));
                for (int i = 0; i < scoreVoList.size(); i++) {
                    JaCompetitionScore jaCompetitionScore1 = new JaCompetitionScore();
                    //条件
                    jaCompetitionScore1.setCompetitionId(scoreVoList.get(i).getCompetitionId());
                    jaCompetitionScore1.setGroupId(scoreVoList.get(i).getGroupId());
                    //修改
                    jaCompetitionScore1.setOrderNum(Long.valueOf(i + 1));
                    jaCompetitionScore1.setResultScorer(scoreVoList.get(i).getResultScorer());
                    jaCompetitionScore1.setUpdateUser(loginUser.getUserid());
                    //jaCompetitionScore1.setScorerId(loginUser.getUserid());
                    //jaCompetitionScore1.setScorerId(loginUser.getUserid());
                    jaCompetitionScoreMapper.updateJaCompetitionScoreByUser1(jaCompetitionScore1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean saveCompetitionFile(List<JaFile> jaFile) {
        try {
            if (!CollectionUtils.isEmpty(jaFile)) {
                JaFile jaFile1 = jaFile.get(0);
                jaFileMapper.deleteJaFile(jaFile1);
                for (JaFile file : jaFile) {
                    jaFileMapper.insertJaFile(file);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteFile(Long id) {
        boolean aa = false;
        try {
            JaFile jaFile1 = new JaFile();
            jaFile1.setForeignKey(id);
            jaFile1.setFlag("2");
            jaFileMapper.deleteJaFile(jaFile1);
            aa = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aa;
    }
    @Override
    public boolean deleteModelFile(Long id) {
        boolean aa = false;
        try {
            JaFile jaFile1 = new JaFile();
            jaFile1.setForeignKey(id);
            jaFile1.setFlag("1");
            jaFileMapper.deleteJaFile(jaFile1);
            aa = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return aa;
    }

    @Override
    public List<SysUser> queryTeacherList() {
        List<SysUser> uniqueUsers = new ArrayList<>();
        List<String> roles = new ArrayList<>();
        roles.add(teacherRole);
        roles.add(judge);
        roles.add(scoring);
        List<SysUser> sysUsers = jaCompetitionManageMapper.queryTeacherList(roles);
        if (CollectionUtil.isNotEmpty(sysUsers)) {
            uniqueUsers = sysUsers.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.collectingAndThen(
                            Collectors.toMap(
                                    SysUser::getUserId,
                                    user -> user,
                                    (existing, replacement) -> existing // 保留第一个出现的
                            ),
                            map -> new ArrayList<>(map.values())
                    ));
        }
        return uniqueUsers;
    }


    @Override
    public List<SysUser> queryAllList(String userName) {
        LoginUser loginUser = tokenService.getLoginUser();
        Map<String, Object> map = new HashMap<>();
        map.put("userName", userName);
        map.put("userId", loginUser.getUserid());
        return jaCompetitionManageMapper.queryAllList(map);
    }

    @Override
    public List<JaCompetitionInvitation> queryGroupUser(Long id) {
        LoginUser loginUser = tokenService.getLoginUser();
        Map<String, Object> map = new HashMap<>();
        map.put("competitionId", id);
        map.put("promoter", loginUser.getUserid());
        List<JaCompetitionInvitation> jaCompetitionInvitations = jaCompetitionInvitationMapper.queryGroupUsers(map);
        return jaCompetitionInvitations;
    }

    @Override
    public boolean checkIsCompetition(Long id) {
        LoginUser loginUser = tokenService.getLoginUser();
        if (loginUser == null) {
            throw new RuntimeException("用户没有登录，请先登录！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("competitionId", id);
        map.put("userId", loginUser.getUserid());
        List<JaGroupUser> jaGroupUsers = jaGroupUserMapper.checkIsCompetition(map);
        if (CollectionUtil.isNotEmpty(jaGroupUsers)) {
            throw new RuntimeException("登陆人已参赛！");
        }
        JaCompetitionManage jaCompetitionManage = jaCompetitionManageMapper.checkCompetitionTime(id);
        if (jaCompetitionManage == null) {
            throw new RuntimeException("比赛报名日期已经截止！");
        }
        return true;
    }

    @Override
    public List<CompetitionGroupVo> queryLoginUserGroup() {
        LoginUser loginUser = tokenService.getLoginUser();
        List<CompetitionGroupVo> jaCompetitionGroups = jaCompetitionGroupMapper.queryLoginUserGroup(loginUser.getUserid());
        return jaCompetitionGroups;
    }
}
